"use strict";


// ws

(function($) {
    $.websocket = function(options) {
        var defaults = {
            domain: top.location.hostname,
            port:3398,
            protocol:""
        };
        var opts = $.extend(defaults,options);
        var szServer = "ws://" + opts.domain + "/" + opts.protocol;
        var socket = null;
        var bOpen = false;
        var t1 = 0; 
        var t2 = 0; 
        var messageevent = {
            onInit:function(){
                if(!("WebSocket" in window) && !("MozWebSocket" in window)){  
                    return false;
                }
                if(("MozWebSocket" in window)){
                    socket = new MozWebSocket(szServer);  
                }else{
                    socket = new WebSocket(szServer);
                }
                if(opts.onInit){
                    opts.onInit();
                }
            },
            onOpen:function(event){
                bOpen = true;
                if(opts.onOpen){
                    opts.onOpen(event);
                }
            },
            onSend:function(msg){
                t1 = new Date().getTime(); 
                if(opts.onSend){
                    opts.onSend(msg);
                }
                socket.send(msg);
            },
            onMessage:function(msg){
                t2 = new Date().getTime(); 
                if(opts.onMessage){
                    opts.onMessage(msg.data,t2 - t1);
                }
            },
            onError:function(event){
                if(opts.onError){
                    opts.onError(event);
                }
            },
            onClose:function(event){
                if(opts.onclose){
                    opts.onclose(event);
                }
                if(socket.close() != null){
                    socket = null;
                }
            }
        }

        messageevent.onInit();
        socket.onopen = messageevent.onOpen;
        socket.onmessage = messageevent.onMessage;
        socket.onerror = messageevent.onError;
        socket.onclose = messageevent.onClose;
        
        this.send = function(pData){
            if(bOpen == false){
                return false;
            }
            messageevent.onSend(pData);
            return true;
        }
        this.close = function(){
            messageevent.onClose();
        }
        return this;
    };
})(jQuery);



(function (factory) {
    typeof define === 'function' && define.amd ? define(factory) :
    factory();
}((function () { 'use strict';

    /**
     * The code was extracted from:
     * https://github.com/davidchambers/Base64.js
     */

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function InvalidCharacterError(message) {
        this.message = message;
    }

    InvalidCharacterError.prototype = new Error();
    InvalidCharacterError.prototype.name = "InvalidCharacterError";

    function polyfill(input) {
        var str = String(input).replace(/=+$/, "");
        if (str.length % 4 == 1) {
            throw new InvalidCharacterError(
                "'atob' failed: The string to be decoded is not correctly encoded."
            );
        }
        for (
            // initialize result and counters
            var bc = 0, bs, buffer, idx = 0, output = "";
            // get next character
            (buffer = str.charAt(idx++));
            // character found in table? initialize bit storage and add its ascii value;
            ~buffer &&
            ((bs = bc % 4 ? bs * 64 + buffer : buffer),
                // and if not first of each 4 characters,
                // convert the first 8 bits to one ascii character
                bc++ % 4) ?
            (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) :
            0
        ) {
            // try to find character in table (0-63, not found => -1)
            buffer = chars.indexOf(buffer);
        }
        return output;
    }

    var atob = (typeof window !== "undefined" &&
        window.atob &&
        window.atob.bind(window)) ||
    polyfill;

    function b64DecodeUnicode(str) {
        return decodeURIComponent(
            atob(str).replace(/(.)/g, function(m, p) {
                var code = p.charCodeAt(0).toString(16).toUpperCase();
                if (code.length < 2) {
                    code = "0" + code;
                }
                return "%" + code;
            })
        );
    }

    function base64_url_decode(str) {
        var output = str.replace(/-/g, "+").replace(/_/g, "/");
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += "==";
                break;
            case 3:
                output += "=";
                break;
            default:
                throw "Illegal base64url string!";
        }

        try {
            return b64DecodeUnicode(output);
        } catch (err) {
            return atob(output);
        }
    }

    function InvalidTokenError(message) {
        this.message = message;
    }

    InvalidTokenError.prototype = new Error();
    InvalidTokenError.prototype.name = "InvalidTokenError";

    function jwtDecode(token, options) {
        if (typeof token !== "string") {
            throw new InvalidTokenError("Invalid token specified");
        }

        options = options || {};
        var pos = options.header === true ? 0 : 1;
        try {
            return JSON.parse(base64_url_decode(token.split(".")[pos]));
        } catch (e) {
            throw new InvalidTokenError("Invalid token specified: " + e.message);
        }
    }

    /*
     * Expose the function on the window object
     */

    //use amd or just through the window object.
    if (window) {
        if (typeof window.define == "function" && window.define.amd) {
            window.define("jwt_decode", function() {
                return jwtDecode;
            });
        } else if (window) {
            window.jwt_decode = jwtDecode;
        }
    }

})));
//# sourceMappingURL=jwt-decode.js.map



var tools = function() {};
//获取url参数
tools.prototype.GetQueryString = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
};

//获取url的token参数
tools.prototype.GetToken = function() {
    var name = 'token'
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    var token = context == null || context == "" || context == "undefined" ? "" : context;
    //临时测试 开始
    //  token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTU4NjM4MzEsIlVzZXJOYW1lIjpudWxsLCJVc2VySWQiOiJhMDFjOWRhODdjMWU0MTczYTIwODlmYjdiZTE1N2RkYSIsInJvbGVzIjpbeyJpZCI6IjhmZDMwMDBjMzE0YzQ0MWZiYjc1M2UzZDdkZWI4ZTRlIiwiUm9sZU5hbWUiOiJ1c2VyIiwiUm9sZUlkIjoiNzU5ZWMwMDFlNGI1NDgwNDg4Nzk1MjA0ZmY4MGFlN2MifV0sInN0YXR1cyI6MSwibmFtZSI6bnVsbCwic2V4IjoiMSIsIkhlYWRTY3VscHR1cmUiOiJodHRwczovL3RoaXJkd3gucWxvZ28uY24vbW1vcGVuL3ZpXzMyL1EzYXVIZ3p3ek00ZUhieXZPOUZpYzNpYWU3cGtJNGo5dkY4b1RDNnVzcGU2RjJoWWR6aWJGUFBrRW9YMlk1d21PZ01obHhscGxlRUx1WGFvSFVOVTd1VVlRLzEzMiIsIk5pY2tOYW1lIjoiXHU2ODExIn0.jwIQb6AGiaI2x6ByZRKHVXa8_2AWSwrbTx4jTHphqys'
    // //临时测试 结束
    return token
};

tools.prototype.getViewPortSize = function(w) {
    var w = w || window;
    if (w.innerWidth) {
        return { width: w.innerWidth, height: w.innerHeight };
    }
    var d = w.document;
    if (d.compatMode == "CSS1Compat") {
        return { width: d.documentElement.clientWidth, height: d.documentElement.clientHeight };
    }
    return { width: d.body.clientWidth, height: d.body.clientHeight };
};
tools.prototype.getScrollOffsets = function(w) {
    var w = w || window;
    if (w.pageXOffset != null) {
        return { scrollX: w.pageXOffset, scrollY: w.pageYOffset };
    }
    var doc = w.document;
    if (doc.compatMode == "CSS1Compat") {
        return { scrollX: doc.documentElement.scrollLeft, scrollY: doc.documentElement.scrollTop };
    }
    return { scrollX: doc.body.scrollLeft, scrollY: doc.body.scrollTop };
};
tools.prototype.getOffset = function(element) {
    var left = 0,
        top = 0;
    var parent = element;
    while (parent != null) {
        left += parent.offsetLeft;
        top += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return { offsetX: left, offsetY: top };
}
tools.prototype.format = function(fmt, objDate) {
    var o = {
        "M+": objDate.getMonth() + 1, //月份
        "d+": objDate.getDate(), //日
        "h+": objDate.getHours(), //小时
        "m+": objDate.getMinutes(), //分
        "s+": objDate.getSeconds(), //秒
        "q+": Math.floor((objDate.getMonth() + 3) / 3), //季度
        "S": objDate.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (objDate.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
tools.prototype.isLeapYear = function(objDate) { //判断闰年
    var pYear = objDate.getFullYear();
    if (!isNaN(parseInt(pYear))) {
        if ((pYear % 4 == 0 && pYear % 100 != 0) || (pYear % 100 == 0 && pYear % 400 == 0)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
};
/***************************************************
 *比较两个日期的间隔
 *参数说明:
 *objDate：结束日期
 *interval要返回的两个日期的间隔,比如：
 *s：返回两个日期相差的秒数
 *n：返回两个日期相差的分钟数
 *h：返回两个日期相差的小时数
 *d：返回两个日期相差的天数
 *w：返回两个日期相差的周数
 *m：返回连个日期相差的月数
 *y：返回连个日期相差的年数
 ****************************************************/
tools.prototype.dateDiff = function(interval, objBeginDate, objEndDate) {
    var dtBegin = new Date(objBeginDate);
    var dtEnd = new Date(objEndDate);
    if (isNaN(dtEnd)) return undefined;
    switch (interval) {
        case "s":
            return parseInt((dtEnd - dtBegin) / 1000);
        case "n":
            return parseInt((dtEnd - dtBegin) / 60000);
        case "h":
            return parseInt((dtEnd - dtBegin) / 3600000);
        case "d":
            return parseInt((dtEnd - dtBegin) / 86400000);
        case "w":
            return parseInt((dtEnd - dtBegin) / (86400000 * 7));
        case "m":
            return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtBegin.getFullYear()) * 12) - (dtBegin.getMonth() + 1);
        case "y":
            return dtEnd.getFullYear() - dtBegin.getFullYear();
    }
};
tools.prototype.createCorrectDate = function(strFormatDate, dateArr) {
    if (strFormatDate == undefined || strFormatDate == null || strFormatDate == '') return 'invalidDate';
    var dateObj;
    try {
        var dateArray;
        if (strFormatDate.indexOf('-') > -1) {
            dateArray = strFormatDate.toString().split('-');
            dateObj = new Date(Number(dateArray[0]), Number(dateArray[1]) - 1, Number(dateArray[2]));
            if (Number(dateArray[0]) != dateObj.getFullYear())
                return 'invalidDate';
            if (Number(dateArray[1]) != dateObj.getMonth() + 1)
                return 'invalidDate';
            if (Number(dateArray[2]) != dateObj.getDate())
                return 'invalidDate';
        } else if (strFormatDate.indexOf('.') > -1) {
            dateArray = strFormatDate.toString().split('.');
            dateObj = new Date(Number(dateArray[0]), Number(dateArray[1]) - 1, Number(dateArray[2]));
            if (Number(dateArray[0]) != dateObj.getFullYear())
                return 'invalidDate';
            if (Number(dateArray[1]) != dateObj.getMonth() + 1)
                return 'invalidDate';
            if (Number(dateArray[2]) != dateObj.getDate())
                return 'invalidDate';
        } else if (strFormatDate.indexOf('/') > -1) {
            dateArray = strFormatDate.toString().split('/');
            dateObj = new Date(Number(dateArray[0]), Number(dateArray[1]) - 1, Number(dateArray[2]));
            if (Number(dateArray[0]) != dateObj.getFullYear())
                return 'invalidDate';
            if (Number(dateArray[1]) != dateObj.getMonth() + 1)
                return 'invalidDate';
            if (Number(dateArray[2]) != dateObj.getDate())
                return 'invalidDate';
        }
        dateArr = dateArr || [];
        for (var i = 0; i < dateArr.length; i++) {
            switch (i) {
                case 0:
                    dateObj.setHours(dateArr[0]);
                    if (dateObj.getHours() != Number(dateArr[0]))
                        return 'invalidDate';
                    break;
                case 1:
                    dateObj.setMinutes(dateArr[1]);
                    if (dateObj.getMinutes() != Number(dateArr[1]))
                        return 'invalidDate';
                    break;
                case 2:
                    dateObj.setSeconds(dateArr[2]);
                    if (dateObj.getSeconds() != Number(dateArr[2]))
                        return 'invalidDate';
                    break;
                case 3:
                    dateObj.setMilliseconds(dateArr[3]);
                    if (dateObj.getMilliseconds() != Number(dateArr[3]))
                        return 'invalidDate';
                default:
                    break;
            }
        }
        if (dateArr.length <= 0) {
            dateObj.setHours(0);
            dateObj.setMinutes(0);
            dateObj.setSeconds(0);
            dateObj.setMilliseconds(0);
        }
        return dateObj;
    } catch (e) {
        return 'invalidDate';
    }
};
tools.prototype.findElementIndex = function(arr, element) {
    for (var i = 0; i < arr.length; i++) {
        if (Object.prototype.toString.call(arr[i]) == "[object Object]") {
            for (var key in arr[i]) {
                if (key == element) {
                    return i;
                }
            }
        } else if (element === arr[i]) {
            return i;
        }
    }
    return -1;
};
tools.prototype.removeElement = function(array, element) {
    var n = tools.prototype.findElementIndex(array, element);
    if (n < 0) {
        return array;
    } else {
        return array.splice(n, 1); //this.slice(0, n).concat(this.slice(n + 1, this.length));
    }
};

tools.prototype.browser = (function() {
    var userAgen = navigator.userAgent.toLowerCase();
    var brower = {};
    var s;
    (s = userAgen.match(/msie ([\d.]+)/)) ? brower.ie = s[1]: (s = userAgen.match(/firefox\/([\d.]+)/)) ? brower.firefox = s[1] :
        (s = userAgen.match(/chrome\/([\d.]+)/)) ? brower.chrome = s[1] :
        (s = userAgen.match(/opera\/.*version\/([\d.]+)/)) ? brower.opera = s[1] :
        (s = userAgen.match(/version\/([\d.]+).*safari/)) ? brower.safari = s[1] :
        0;

    if (/webkit/.test(userAgen))
        brower.webkit = userAgen.match(/webkit\/([\d.]+)/)[1];
    return brower;
})();
tools.prototype.resetImageSize = function(ImgD, iwidth, iheight, center) {
    var image = new Image();
    image.src = ImgD.src;
    if (image.width > 0 && image.height > 0) {
        if (image.width / image.height >= iwidth / iheight) {
            if (image.width > iwidth) {
                ImgD.width = iwidth;
                ImgD.height = (image.height * iwidth) / image.width;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        } else {
            if (image.height > iheight) {
                ImgD.height = iheight;
                ImgD.width = (image.width * iheight) / image.height;
            } else {
                ImgD.width = image.width;
                ImgD.height = image.height;
            }
        }
        if (center) {
            ImgD.parentNode.style.marginTop = (iheight - ImgD.height) / 2;
            ImgD.parentNode.style.marginLeft = (iwidth - ImgD.width) / 2;
        }
    }
};
tools.prototype.getQuery = function(queryKey, target, pattern) {
    var locationSearch = location.search;
    if (target) locationSearch = target;
    var regExp = new RegExp("" + queryKey + "=([^&=]+)");
    if (pattern) regExp = pattern;
    var query;
    if (regExp.test(locationSearch)) {
        query = RegExp.$1;
    }
    return query;
};
tools.prototype.trim = function(value) {
    var regEx = /(^\s*|\s*$)$/gi;
    return value.replace(regEx, "");
};
tools.prototype.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var regExp = new RegExp("" + name + "=([^;=]+)");
            if (regExp.test(document.cookie)) {
                cookieValue = RegExp.$1;
            }
        }
        return cookieValue;
    }
};
tools.prototype.unique = function(arr) {
    var res = [];
    var json = {};
    for (var i = 0; i < arr.length; i++) {
        if (!json[arr[i]]) {
            res.push(arr[i]);
            json[arr[i]] = 1;
        }
    }
    return res;
};
module.exports = new tools();